package common {

	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;
	
	import net.message.BaseMessage;
	
	import util.Logger;
	
	public class HTTPService extends URLStream {
		
		private var url:String;
		public var handler:Function;
		public var rawData:ByteArray;
		private var _request:URLRequest;

		public function HTTPService(host:String) {
			super();
			
			url = host;
			
			addEventListener(Event.COMPLETE, completeHandler);
			addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityHandler);
		}
		
		public function send(message:BaseMessage):void {
			_request = new URLRequest(url);
			_request.method = "post";
//			_request.contentType = "text/html; charset=utf-8";
			var data:ByteArray = new ByteArray();
			
			// 先
			data.writeInt(message.type);
			data.writeShort(message.type);
			
			_request.data = message.body;
			super.load(_request);
		}
		
		protected function completeHandler(event:Event):void {
			var byteArray:ByteArray = new ByteArray();
			readBytes(byteArray);
			if (handler != null) {
				handler(byteArray);
			}
		}
		
		private function errorHandler(event:IOErrorEvent):void {Logger.error(event.toString())};
		private function securityHandler(event:SecurityErrorEvent):void {Logger.error(event.toString())};
	}
}